<?php

namespace app\api\controller;

use app\api\model\Article;
use app\api\model\Comment as ModelComment;
use app\api\model\User as ModelUser;
use app\api\service\ForbiddenWordService;
use app\api\service\Token;
use app\api\validate\Comment as ValidateComment;
use app\common\LogService;
use app\common\Notification;
use think\exception\ValidateException;
use think\facade\Db;

class Comment extends Base
{
    // 我的评论 | 查看别人的文章
    public function index($id = 0)
    {
        ModelComment::$uid =   $id == 0 ? $this->uid : $id;
        $list = ModelComment::list();
        return $list;
    }
    // 文章评论
    public function list($id)
    {
        ModelComment::$art_id = $id;
        $list = ModelComment::list();
        return $list;
    }
    public function add()
    {
        $param = input('post.');
        try {
            validate(ValidateComment::class)->check($param);
            $art = Article::where(['id' => $param['id'], 'status' => 1]);
            if ($art->findOrEmpty()->isEmpty()) return error('文章不存在');
            $artData = $art->find();
            $limitCheck = $this->checkMessageLimit();
            // 发送消息限制
            if (!$limitCheck['status']) {
                return error($limitCheck['msg']);
            }
            if ($artData['type'] == '3') {
                if (!Article::checkHasPay($artData['id'])) {
                    Db::name('payedArt')->insert(['art_id' => $param['id'], 'user_id' => $this->uid]);
                }
            }
            $comment = ModelComment::where(['id' => @$param['pid']])->find();
            $author_id = $artData['user_id'];
            $content = ForbiddenWordService::checkText($param['comment']);
            if ($comment) {
                $response_user = ModelUser::find($comment['user_id']);
                if ($response_user) {
                    $msg = "你的评论:" . $comment['comment'] . '被回复:' . $content;
                    Notification::send($comment['user_id'], $msg, 2, $artData['id']);
                }
            }
            if ($author_id != $this->uid) {
                $msg = '你的文章 《' . $artData['title'] . '》收到了一条评论：' . $content;
                Notification::send($author_id, $msg, 2, $artData['id']);
            }
            $floor = $artData['comment'];
            $data = [
                'comment' => $content,
                'pid' => isset($param['pid']) ? $param['pid'] : 0,
                'art_id' => $param['id'],
                'floor' => ++$floor,
                'user_id' => $this->uid
            ];
            $res = ModelComment::create($data);
            LogService::record(
                user_id: getUid(),
                name: '发表评论',
                target_id: $param['id'],
                content: $data
            );
            if ($res) {
                $art->inc('comment', 1)->update();
                $userInfo = (new Token)->getTokenVal($this->token);
                $result = [
                    'art_id' => $param['id'],
                    'comment' => $content,
                    'create_time' => $res->create_time,
                    'floor' => $floor,
                    'id' => $res->id,
                    'userInfo' => $userInfo
                ];
                if ($res->pid != 0) {
                    $parentComment = ModelComment::find($res->pid);
                    $result['parent_comment'] = $parentComment ? $parentComment['comment'] : '该评论已被删除';
                    $result['parent_user'] = $parentComment ? ModelUser::field('id,avator,signature,nickname')->find($parentComment['user_id']) : [];
                    $result['pid'] = $res->pid;
                }
                return success($result);
            }
            return error();
        } catch (ValidateException $e) {
            return error($e->getError());
        }
    }
    // 消息发送限制
    public function checkMessageLimit()
    {
        $userId = $this->uid;
        $redisKey = "msg_limit:{$userId}:" . date('YmdHi');

        try {
            // 使用 Cache 门面操作 Redis
            $cache = \think\facade\Cache::store('redis');

            // 获取当前计数
            $count = $cache->get($redisKey, 0);
            $count++;

            // 设置新的计数和过期时间
            $cache->set($redisKey, $count, 60);  // 60秒过期

            // 检查频率限制
            if ($count > 30) {
                $ttl = 60 - (time() - strtotime(date('YmdHi') . '00'));
                return [
                    'status' => false,
                    'msg' => "发送过于频繁，请 {$ttl} 秒后重试",
                    'wait_seconds' => $ttl
                ];
            }

            return ['status' => true];
        } catch (\Exception $e) {
            \think\facade\Log::error('消息频率限制检查异常: ' . $e->getMessage());
            return ['status' => true];
        }
    }
    public function del($id)
    {
        $recordLog = function ($status, $message = '') {
            LogService::record(
                name: '删除评论',
                user_id: $this->uid,
                status: $status,
                content: $message == '' ? [] : ['reason' => $message],
            );
        };
        $comment = ModelComment::with('articleInfo', function ($query) {
            $query->field('id , user_id');
        })->where(['id' => $id])->find();
        if (!$comment) {
            $recordLog(0, '评论不存在');
            return error('评论不存在');
        }
        if ($comment->articleInfo->user_id == $this->uid || $this->uid == $comment->user_id) {
            $res = ModelComment::destroy($id);
            if ($res) return success();
            return error();
        }
    }
}
